# -*- coding: utf8 -*-

class ResultFilter(object):
  """Interface for search result filters."""
  
  def __init__(self, options):
    """
    Constructor for ResultFilter.
    
    During initialisation, the filter will use its class name to name itself.  This classname should match the Python file containing the class, otherwise reflection in the framework becomes tricky.
    
    Besides the name, filters also have a short description of what they do, and a dictionary of options to customise the filter.
    
    Parameters:
    
    * options (str): a long-format unix command line option string, e.g. --time=10.  It is important to use the long-format notation!
    """
    super(ResultFilter, self).__init__()
    self.name = self.__class__.__name__
    self.info = "<<<please describe this filter!>>>"
    self.options = self.parse_options(options)
  
  def run(self, results):
    """
    Filters the set of results.
    
    Parameters:
      
    * results (puppy.model.Opensearch.Response): results to be filtered
    
    Returns:
    
    * results (puppy.model.Opensearch.Response): filtered results
    """
    return results
  
  
  def parse_options(self, options):
    """
    Parse options for filter.
    
    Filters may expose an arbitrary number of options that can customise their behaviour.  The options string can contain any number of long form unix command line options (e.g. - -time=10) that are separated by a space.
    
    Parameters:
      
    * options (str): a string of unix command line options to be parsed
    
    Returns:
      parsed_options (dict): a map of available options for this filter
      
    Raises:
    
    * Exception: caused by malformed option
    
    TODO substitute spaces with plus in parsed_options(options)
    """
    import optparse
    try:
      parser = optparse.OptionParser()
      option_list = options.split()
      for option in option_list:
        option_name = option.split('=')[0]
        parser.add_option(option_name, action='store', dest=option_name[2:])
      parsed_options = vars(parser.parse_args(option_list)[0])
      return parsed_options
    except Exception as e:
      print e

